package org.studiox.graph.persistence.spring.jdbc.dao.impl;

import org.springframework.jdbc.core.JdbcTemplate;
import org.studiox.graph.persistence.model.GraphVertexDO;
import org.studiox.graph.persistence.spring.jdbc.dao.GraphVertexDao;
import org.studiox.graph.persistence.spring.jdbc.rowmapper.GraphVertexDOMapper;

import java.util.List;

public class GraphVertexDaoImpl implements GraphVertexDao {

  private JdbcTemplate jdbcTemplate;

  public GraphVertexDaoImpl(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  @Override
  public List<GraphVertexDO> findAll() {
    String sql = "select * from graph_vertex";
    return jdbcTemplate.query(sql, new GraphVertexDOMapper());
  }

  @Override
  public int save(GraphVertexDO graphVertexDO) {
    String sql =
        "insert into graph_vertex(uniq,type,owner,janus_vertex_id,temp) values (?,?,?,?,?)";
    Object[] obj =
        new Object[] {
          graphVertexDO.getUniq(),
          graphVertexDO.getType(),
          graphVertexDO.getOwner(),
          graphVertexDO.getJanusVertexId(),
          graphVertexDO.getTemp()
        };
    return jdbcTemplate.update(sql, obj);
  }

  @Override
  public int update(GraphVertexDO graphVertexDO) {
    String sql =
        "update graph_vertex set uniq=?,type=?,owner=?,janus_vertex_id=?,temp=?,deleted=?,update_time=? where id=?";
    Object[] obj =
        new Object[] {
          graphVertexDO.getUniq(),
          graphVertexDO.getType(),
          graphVertexDO.getOwner(),
          graphVertexDO.getJanusVertexId(),
          graphVertexDO.getTemp(),
          graphVertexDO.getDeleted(),
          graphVertexDO.getUpdateTime(),
          graphVertexDO.getId()
        };
    return jdbcTemplate.update(sql, obj);
  }

  @Override
  public int delete(Long id) {
    String sql = "delete from graph_vertex where id=?";
    return jdbcTemplate.update(sql, id);
  }

  @Override
  public GraphVertexDO findById(Long id) {
    String sql = "select * from graph_vertex where id=?";
    return jdbcTemplate.queryForObject(sql, new GraphVertexDOMapper(), id);
  }

  @Override
  public int findTotalNum() {
    String sql = "select count(*) from graph_vertex";
    return jdbcTemplate.queryForObject(sql, (rs, rowNum) -> rs.getInt(1));
  }
}
